package com.flower.sharding;

import com.common.baseException.ExceptionEnum;
import com.common.baseException.ShardingException;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.sharding.api.sharding.standard.PreciseShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.RangeShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.StandardShardingAlgorithm;

import java.math.BigInteger;
import java.util.Arrays;
import java.util.Collection;

/**
 * @ClassName TablePreciseAlgorithm
 * @Description TODO
 * @Author 张晓焕
 * @Date 2022/6/10 16:47
 * @Version 1.0
 */
@Slf4j
public class TablePreciseAlgorithm implements StandardShardingAlgorithm<Long> {
    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<Long> preciseShardingValue) {


        log.info("分库策略执行");
        log.info(String.valueOf(collection));
        log.info(preciseShardingValue.toString());
        final String logicTableName = preciseShardingValue.getLogicTableName();
        //分片列的值
        final Long value = preciseShardingValue.getValue();
        final BigInteger bigInteger = BigInteger.valueOf(value);
        final BigInteger mod = bigInteger.mod(BigInteger.valueOf(2));
        log.info(String.valueOf(mod));
        String tableName=logicTableName+"_"+mod;
        if (collection.contains(tableName)) {
            return tableName;
        }
        throw new ShardingException(ExceptionEnum.SHARING_ERROR);
    }

    @Override
    public Collection<String> doSharding(Collection<String> collection, RangeShardingValue<Long> rangeShardingValue) {
        log.info("表范围查询");
        log.info(String.valueOf(collection));
        log.info(rangeShardingValue.getLogicTableName());
        log.info(String.valueOf(rangeShardingValue.getValueRange().upperEndpoint()));
        log.info(String.valueOf(rangeShardingValue.getValueRange().lowerEndpoint()));
        return Arrays.asList("t_order_0","t_order_1");
    }

    @Override
    public void init() {
        log.info("表规则初始化");
    }

    @Override
    public String getType() {
        return "TABLE_STRATEGY";
    }
}
